package com.jp.knowledge.http;

import com.google.gson.JsonObject;
import com.jp.knowledge.model.NetLogModel;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.NetLogUtil;
import com.jp.knowledge.util.TimeUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Locale;
import java.util.zip.GZIPInputStream;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by jiayen on 16/9/28.
 */
public class HttpInterceptor implements Interceptor {

    private static String TAG = "HTTP-Interceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        //封装headers
        Request request = chain.request().newBuilder()
//                .addHeader("Content-Type", "application/json") //TODO 添加请求头信息,和后台协调编码，不过通常都是utf-8
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=gbk")
                .build();
////        Headers headers = request.headers();
//        String requestUrl = request.url().toString(); //获取请求url地址
//        String methodStr = request.method(); //获取请求方式
//        RequestBody body = request.body(); //获取请求body
//        String bodyStr = (body==null?"":body.toString());
//        //打印Request数据
//        L.i("HTTP-Interceptor","requestUrl=====>"+requestUrl);
        L.i("HTTP-Interceptor","requestMethod=====>"+chain.request().method());
//        L.i(TAG, "requestHeaders=====>" + request.headers());
        //  Content-Encoding: gzip
        L.i(TAG, "request:" + request.toString());
//        long t1 = System.nanoTime();
        long t1 = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());
//        long t2 = System.nanoTime();
        long t2 = System.currentTimeMillis();
        L.i(TAG, String.format(Locale.getDefault(), "Received response for %s in (%.1fms)%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        Long content_length = response.body().contentLength();
        ResponseBody responseBody;
        if (content_length < 0) {
            responseBody = response.peekBody(1024 * 4);
        } else {
            responseBody = response.peekBody(content_length);
        }

//        NetLogModel netLogModel = new NetLogModel();
//        netLogModel.setType("Android");
//        netLogModel.setRequestTime(TimeUtil.dateFormater.get().format(new Date(t1)));
//        netLogModel.setResponseTime(TimeUtil.dateFormater.get().format(new Date(t2)));
//        netLogModel.setUrl(request.url().toString());

        String type =response.headers().get("Content-Encoding");
        if(type!=null&&type.equals("gzip")) {
            String responseStr = doUnGzip(responseBody);
            if(responseStr.indexOf("非法的")!=-1){
                L.e("error_code",request.url().toString());
            }
            try {
//                JsonObject responseData = JsonUtil.getInstance().strToJson(responseStr);
//                netLogModel.setErrorCode(responseData.get("errcode").getAsInt());
//                netLogModel.setMessage(responseData.get("message").getAsString());
                if (request.body() instanceof FormBody) {
                    FormBody requestBody = (FormBody) request.body();
                    for (int i = 0; i < requestBody.size(); i++) {
                        if (!"data".equals(requestBody.encodedName(i)))
                            continue;
//                        netLogModel.setRequestParam(URLDecoder.decode(requestBody.encodedValue(i), "utf-8"));
                        break;
                    }
                }
            } catch (Exception e){
//                netLogModel.setMessage(e.toString());
            }
            L.i(TAG, "do unGzip response body:" + responseStr);
        }else{
            if(responseBody.toString().indexOf("非法的")!=-1){
                L.e("error_code",request.url().toString());
            }
//            netLogModel.setErrorCode(response.code());
//            netLogModel.setMessage(response.message());
            L.i(TAG, "response body:" + responseBody.toString());
        }

//        NetLogUtil.saveNetMsgToLocal(netLogModel);
        return response;
    }


    private String doUnGzip(ResponseBody responseBody){
        GZIPInputStream  in = null;
        try {
            in = new GZIPInputStream( responseBody.byteStream());
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                arrayOutputStream.write(buffer, 0, len);
            }
            in.close();
            arrayOutputStream.close();
            String str = new String(arrayOutputStream.toByteArray(), "utf-8");
//        Debug.i_MrFu("做了解压的数据 = " + str);
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "do unzip error";
    }
}
